package org.springblade.job.executor.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.api.R;
import org.springblade.system.partybuild.feign.IPartyBuildClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 获取习大大重要讲话
 * <p>
 * 开发步骤：
 * 1、在Spring Bean实例中，开发Job方法，方式格式要求为 "public ReturnT<String> execute(String param)"
 * 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author hfz
 */
@Component
public class SpeechDatabaseJob {
	private static final Logger logger = LoggerFactory.getLogger(SpeechDatabaseJob.class);

	@Autowired
	private IPartyBuildClient partyBuildClient;

	/**
	 * 1、同步组织机构（Bean模式）
	 */
	@XxlJob("syncSpeechDatabaseJobHandler")
	public ReturnT<String> syncSpeechDatabaseJobHandler(String param) throws Exception {
		String url = "http://jhsjk.people.cn/";
		Document doc = Jsoup.parse(new URL(url), 6000);
		Elements newsBox = doc.getElementsByClass("news-box");
		Element news = newsBox.get(0).getElementsByClass("news").get(0);
		Elements ul = news.getElementsByTag("li");
		if (ul == null || ul.size() == 0) {
			return ReturnT.SUCCESS;
		}
		//List<Map<String, String>> mapList = new ArrayList<>();
		Collections.reverse(ul);
		for (Element li : ul) {
			Map<String, Object> map = new HashMap<>();

			Element a = li.getElementsByTag("a").get(0);
			//System.out.println("url   ---> " + a.attr("href"));
			String href = a.attr("href");
			map.put("speechUrl", url + href);

			Element span = a.getElementsByTag("span").get(0);
			//System.out.println("title  --> " + span.text());
			map.put("speechTitle", span.text());

			Element i = a.getElementsByTag("i").get(0);
			//System.out.println("source---> " + i.text());
			String sourceText = i.text();
			map.put("speechSource", sourceText);
			String sDate = sourceText.substring(sourceText.indexOf('【') + 1, sourceText.length()-1);
			//DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			map.put("speechDate", sDate);

			Document con = Jsoup.parse(new URL(url + href), 6000);
			Element conDiv = con.getElementsByClass("d2txt").get(0);
			map.put("speechContent", conDiv.html());

			try {
				partyBuildClient.saveSpeechData(map);
			}catch (Exception e){
				e.printStackTrace();
				logger.error(e.getMessage());
			}
			//mapList.add(map);
		}

		return ReturnT.SUCCESS;

	}
}
